package com.flot.yazb.retrofit.service;


import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.app.NotificationCompat;
import android.util.Log;

import com.flot.yazb.R;
import com.flot.yazb.base.BApplication;
import com.flot.yazb.base.model.BModel;
import com.flot.yazb.aop.stub.CodeStub;
import com.flot.yazb.model.nearly.TranslatingModel;
import com.flot.yazb.home.moudle.message.ChatActivity;

import java.util.Arrays;
import java.util.concurrent.LinkedBlockingQueue;



public class LunchService extends Service {

    public static String TAG = LunchService.class.getSimpleName();
    private MyBinder mBinder = new MyBinder();
    private int maxMessageList=40;
    private LinkedBlockingQueue<TranslatingModel> mChatMessageList = new LinkedBlockingQueue(maxMessageList);
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate: ");
    }


    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.d(TAG, "onStart: ");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: ");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d(TAG, "onUnbind: ");
        handler.removeCallbacks(runnable);
        return super.onUnbind(intent);
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
        Log.d(TAG, "onRebind: ");
        handler.postDelayed(runnable, 3*60*1000); //每隔5s执行
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "onBind: ");
        return mBinder;
    }

    Handler handler = new Handler();
    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            // handler自带方法实现定时器
            try {
                handler.postDelayed(this, 3*60*1000);
                if (mChatMessageList.size()>0){
                    showNotifiCation(getBaseContext(),mChatMessageList.poll());
                }else{
                    getMessageCached();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    public void showNotifiCation(Context activity,TranslatingModel model) {
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(activity);
        Intent intent = new Intent(activity, ChatActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("name",model.name);
        intent.putExtra("mid",model.mid);
//        intent.putExtra("cached",cachedModel);
        PendingIntent contentIntent = PendingIntent.getActivity(activity, Integer.parseInt(model.mid), intent, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentTitle(model.name)
                .setContentText(model.content)
                .setContentIntent(contentIntent)
//                .setNumber(5) //设置通知集合的数量
                .setTicker(model.name+"和您打招呼啦")
                .setWhen(System.currentTimeMillis())
                .setPriority(Notification.PRIORITY_DEFAULT)
                .setAutoCancel(true)
                .setOngoing(false)
                .setDefaults(Notification.DEFAULT_VIBRATE)

                .setSmallIcon(R.mipmap.ic_launcher)
        ;
        mNotificationManager.notify(Integer.parseInt(model.mid), mBuilder.build());
    }


    public void sendNotice() {
        getMessageCached();
    }

    /**
     * 获取打招呼数据，然后存储内存
     */
    private void getMessageCached() {
        TranslatingModel.transPeople(BApplication.getInstance().getUserModel().id, new BModel.Transit<TranslatingModel[]>(this) {
            @Override
            public void onBorn(TranslatingModel[] serializable, String code, String message) {
                if (code.equals(CodeStub.B_OK) && serializable!=null){
                    mChatMessageList.addAll(Arrays.asList(serializable));
                    handler.postDelayed(runnable, 15000);
                }else{
                    getMessageCached();
                }
            }
        });
    }

    public class MyBinder extends Binder {
        public LunchService getService() {
            return LunchService.this;
        }
    }
}
